package com.wei.czz.framework.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wei.czz.common.enums.CommonEnum;
import com.wei.czz.common.enums.ResultEnum;
import com.wei.czz.common.exception.CzzException;
import com.wei.czz.common.po.UserPo;
import com.wei.czz.common.utils.SecurityUtils;
import com.wei.czz.common.vo.common.UpdateStatusVo;
import com.wei.czz.common.vo.store.StoreBossVo;
import com.wei.czz.framework.store.dao.StoreBossDao;
import com.wei.czz.framework.store.entity.StoreBossEntity;
import com.wei.czz.framework.store.service.StoreBossService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;


@Service("storeBossService")
@AllArgsConstructor
public class StoreBossServiceImpl extends ServiceImpl<StoreBossDao, StoreBossEntity> implements StoreBossService {

    private static final Logger log = LoggerFactory.getLogger(StoreBossServiceImpl.class);

    @Override
    public Long saveStoreBoss(StoreBossVo storeBossVo) {
        Long id = storeBossVo.getId();
        if (Objects.nonNull(id)) {
            // 修改
            StoreBossEntity storeBoss = baseMapper.selectById(id);
            if (Objects.isNull(storeBoss)) {
                throw new RuntimeException("商店老板不存在");
            }
            // 属性赋值
            this.buildStoreBoss(storeBossVo, storeBoss);

            int count = baseMapper.updateById(storeBoss);
            log.info("修改商店老板完成。count={}", count);
        } else {
            // 添加
            StoreBossEntity storeBoss = this.buildStoreBoss(storeBossVo, null);
            int count = baseMapper.insert(storeBoss);
            log.info("添加商店老板完成。count={}", count);
            id = storeBoss.getId();
        }
        return id;
    }

    @Override
    public Long saveStoreBoss(StoreBossEntity storeBoss) {
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        storeBoss.setId(null)
                .setStatus(CommonEnum.ZERO.getValue())
                .setDefaultStatus(CommonEnum.ZERO.getValue())
                .setDeleteStatus(CommonEnum.ZERO.getValue())
                .setUpdateUser(StringUtils.EMPTY)
                .setUpdateUserId(CommonEnum.ZERO.getLongValue())
                .setCreateTime(date)
                .setCreateUser(userPo.getUsername())
                .setCreateUserId(userPo.getUserId());
        int count = baseMapper.insert(storeBoss);
        log.info("添加商店老板完成.count={}", count);
        return storeBoss.getId();
    }

    @Transactional
    @Override
    public void copyStoreBoss(Long preStoreId, Long storeId) {
        log.info("开始复制商店老板。preStoreId={} storeId={}", preStoreId, storeId);
        LambdaQueryWrapper<StoreBossEntity> storeBossLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeBossLambdaQueryWrapper.eq(StoreBossEntity::getStoreId, preStoreId)
                .eq(StoreBossEntity::getDefaultStatus, CommonEnum.ONE.getValue())
                .eq(StoreBossEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 查询
        List<StoreBossEntity> storeBossList = baseMapper.selectList(storeBossLambdaQueryWrapper);
        if (storeBossList.isEmpty()) {
            log.info("可复制商店老板为空");
        }
        Date date = new Date();

        for (StoreBossEntity storeBoss : storeBossList) {
            storeBoss.setId(null)
                    .setStoreId(storeId)
                    .setUpdateTime(date)
                    .setUpdateUser(StringUtils.EMPTY)
                    .setUpdateUserId(CommonEnum.ZERO.getLongValue())
                    .setCreateTime(date);
        }
        // 批量保存
        boolean bool = this.saveBatch(storeBossList);

        log.info("复制商店老板完成。bool={}", bool);
    }

    @Override
    public List<StoreBossEntity> getStoreDefaultBossList(List<Long> storeIdList) {

        LambdaQueryWrapper<StoreBossEntity> storeBossLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 匹配条件
        storeBossLambdaQueryWrapper.in(StoreBossEntity::getStoreId, storeIdList)
                .eq(StoreBossEntity::getDefaultStatus, CommonEnum.ZERO.getValue())
                .eq(StoreBossEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        List<StoreBossEntity> storeBossList = baseMapper.selectList(storeBossLambdaQueryWrapper);
        log.info("查询商店默认老板完成。size={}", storeBossList.size());
        return storeBossList;
    }

    @Override
    public StoreBossEntity getStoreDefaultBoss(Long storeId) {
        LambdaQueryWrapper<StoreBossEntity> storeBossLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 匹配条件
        storeBossLambdaQueryWrapper.eq(StoreBossEntity::getStoreId, storeId)
                .eq(StoreBossEntity::getDefaultStatus, CommonEnum.ZERO.getValue())
                .eq(StoreBossEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        storeBossLambdaQueryWrapper.last(" limit 1");
        List<StoreBossEntity> storeBossList = baseMapper.selectList(storeBossLambdaQueryWrapper);
        log.info("查询商店默认老板完成。size={}", storeBossList.size());
        if (storeBossList.isEmpty()) {
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "商店老板不存在");
        }
        return storeBossList.get(0);
    }

    @Override
    public List<StoreBossEntity> getStoreBossList(Long storeId) {
        LambdaQueryWrapper<StoreBossEntity> storeBossLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 匹配条件
        storeBossLambdaQueryWrapper.eq(StoreBossEntity::getStoreId, storeId)
                .eq(StoreBossEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        List<StoreBossEntity> storeBossList = baseMapper.selectList(storeBossLambdaQueryWrapper);
        if (storeBossList.isEmpty()) {
            log.info("查询商店老板结果为空。storeId={}", storeId);
        }
        return storeBossList;
    }

    @Override
    public StoreBossEntity getStoreAuditBoss(Long storeId) {
        if (Objects.isNull(storeId)) {
            log.info("传入的商店主键为空");
            return null;
        }
        LambdaQueryWrapper<StoreBossEntity> storeBossLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeBossLambdaQueryWrapper.eq(StoreBossEntity::getStoreId, storeId)
                .eq(StoreBossEntity::getAuditStatus, CommonEnum.ZERO.getValue())
                .eq(StoreBossEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        storeBossLambdaQueryWrapper.last(" limit 1");
        // 查询
        List<StoreBossEntity> storeBossList = baseMapper.selectList(storeBossLambdaQueryWrapper);
        if (storeBossList.isEmpty()) {
            log.info("查询商店正在审核中的老板结果为空。storeId={}", storeId);
            return null;
        }
        return storeBossList.get(0);
    }

    @Override
    public List<StoreBossEntity> batchGetStoreAuditBoss(Collection<Long> storeIdCollection, Integer deleteStatus) {
        if (CollectionUtils.isEmpty(storeIdCollection)) {
            log.info("传入的商店主键集合为空");
            return Collections.emptyList();
        }
        LambdaQueryWrapper<StoreBossEntity> storeBossLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeBossLambdaQueryWrapper.in(StoreBossEntity::getStoreId, storeIdCollection)
                .eq(StoreBossEntity::getAuditStatus, CommonEnum.ZERO.getValue())
                .eq(Objects.nonNull(deleteStatus), StoreBossEntity::getDeleteStatus, deleteStatus);
        // 查询
        List<StoreBossEntity> storeBossList = baseMapper.selectList(storeBossLambdaQueryWrapper);
        if (storeBossList.isEmpty()) {
            log.info("批量查询商店正在审核中的老板结果为空。storeIdCollection={} deleteStatus={}", storeIdCollection,
                    deleteStatus);
        }
        return storeBossList;
    }

    @Override
    public Integer getNextSort(Long storeId) {
        Integer maxSort = baseMapper.selectMaxSort(storeId, CommonEnum.ZERO.getValue());
        if (Objects.isNull(maxSort)) {
            maxSort = 0;
        }
        return maxSort + 1;
    }

    @Override
    public StoreBossEntity getStoreBoss(Long id) {
        StoreBossEntity storeBoss = baseMapper.selectById(id);
        if (Objects.isNull(storeBoss)) {
            log.info("商店老板不存在。id={}", id);
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "商店老板不存在");
        }
        if (CommonEnum.ONE.getValue().equals(storeBoss.getDeleteStatus())) {
            log.info("商店老板已删除。id={}", id);
            throw new CzzException(ResultEnum.REQUEST_FAIL.getCode(), "商店老板不存在");
        }
        return storeBoss;
    }

    @Override
    public void updateStoreBoss(StoreBossEntity storeBoss) {
        if (Objects.isNull(storeBoss.getId())) {
            log.info("传入的商店老板主键为空。{}", storeBoss);
            throw new CzzException();
        }
        int count = baseMapper.updateById(storeBoss);
        log.info("修改商店老板完成。count={}", count);
    }

    @Override
    public void updateStoreBossStatus(UpdateStatusVo updateStatusVo) {
        // 获取操作用户
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        LambdaUpdateWrapper<StoreBossEntity> storeBossLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        storeBossLambdaUpdateWrapper.set(StoreBossEntity::getStatus, updateStatusVo.getStatus())
                .set(StoreBossEntity::getUpdateTime, date)
                .set(StoreBossEntity::getUpdateUser, userPo.getUsername())
                .set(StoreBossEntity::getUpdateUserId, userPo.getUserId());
        storeBossLambdaUpdateWrapper.in(StoreBossEntity::getId, updateStatusVo.getIdList())
                .eq(StoreBossEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 更新
        int count = baseMapper.update(null, storeBossLambdaUpdateWrapper);
        log.info("修改商店老板状态完成。count={}", count);
    }

    @Override
    public void deleteStoreBoss(Long id) {
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();

        LambdaUpdateWrapper<StoreBossEntity> storeBossLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        storeBossLambdaUpdateWrapper.set(StoreBossEntity::getDeleteStatus, CommonEnum.ONE.getValue())
                .set(StoreBossEntity::getUpdateTime, date)
                .set(StoreBossEntity::getUpdateUser, userPo.getUsername())
                .set(StoreBossEntity::getUpdateUserId, userPo.getUserId());
        storeBossLambdaUpdateWrapper.eq(StoreBossEntity::getId, id)
                .eq(StoreBossEntity::getDeleteStatus, CommonEnum.ZERO.getValue());
        // 删除
        int count = baseMapper.update(null, storeBossLambdaUpdateWrapper);
        log.info("删除商店老板完成。count={}", count);
    }

    /**
     * 构建商店老板对象
     * @param storeBossVo 参数对象
     * @param storeBoss   商店老板对象
     * @return 商店老板对象
     */
    private StoreBossEntity buildStoreBoss(StoreBossVo storeBossVo, StoreBossEntity storeBoss) {
        UserPo userPo = SecurityUtils.getUser();
        Date date = new Date();
        boolean isUpdate = Objects.nonNull(storeBoss);
        if (!isUpdate) {
            storeBoss = new StoreBossEntity();
        }

        storeBoss.setStoreId(storeBossVo.getStoreId())
                .setName(Optional.ofNullable(storeBossVo.getName()).orElse(StringUtils.EMPTY))
                .setGender(Optional.ofNullable(storeBossVo.getGender()).orElse(CommonEnum.MINUS_ONE.getValue()))
                .setIdCard(Optional.ofNullable(storeBossVo.getIdCard()).orElse(StringUtils.EMPTY))
                .setMobile(Optional.ofNullable(storeBossVo.getMobile()).orElse(StringUtils.EMPTY))
                .setSort(Optional.ofNullable(storeBossVo.getSort()).orElse(CommonEnum.ONE.getValue()))
                .setStatus(CommonEnum.ZERO.getValue())
                .setDefaultStatus(
                        Optional.ofNullable(storeBossVo.getDefaultStatus())
                                .orElse(CommonEnum.ZERO.getValue())
                )
                .setAuditStatus(Optional.ofNullable(storeBossVo.getAuditStatus()).orElse(CommonEnum.ONE.getValue()))
                .setDeleteStatus(CommonEnum.ZERO.getValue())
                .setUpdateTime(date);
        if (isUpdate) {
            storeBoss.setUpdateUser(userPo.getUsername())
                    .setUpdateUserId(userPo.getUserId());
        } else {
            storeBoss.setUpdateUser(StringUtils.EMPTY)
                    .setUpdateUserId(CommonEnum.ZERO.getLongValue())
                    .setCreateTime(date)
                    .setCreateUser(userPo.getUsername())
                    .setCreateUserId(userPo.getUserId());
        }
        return storeBoss;
    }

}